package com.guard.agent.bridge;

import jdk.nashorn.internal.runtime.linker.Bootstrap;

import java.lang.reflect.Method;

public class LoggerProxy {

    private static Class<?> LOGGER = null;

    private static Method INFO = null;

    private static Method INFO_1 = null;

    private static Method ERROR = null;

    private static Class<?> getTargetClass() {
        if (LOGGER == null) {
            try {
                LOGGER = AgentContext.agentClassLoader.loadClass("org.tinylog.Logger");
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
        return LOGGER;
    }

    private static Method getTargetMethod(String name, Class<?>... parameterTypes) {
        Class<?> logger = getTargetClass();
        if (logger != null) {
            try {
                return logger.getMethod(name, parameterTypes);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
        return null;
    }

    private static Method getInfoMethod() {
        if (INFO == null) {
            INFO = getTargetMethod("info", Object.class);
        }
        return INFO;
    }

    private static Method getInfo1Method() {
        if (INFO_1 == null) {
            INFO_1 = getTargetMethod("info", String.class, Object[].class);
        }
        return INFO_1;
    }

    private static Method getErrorMethod() {
        if (ERROR == null) {
            ERROR = getTargetMethod("error", Throwable.class, String.class, Object[].class);
        }
        return ERROR;
    }

    private static void invoke(Method method, Object... args) {
        if (method == null) {
            return;
        }
        try {
            method.invoke(null, args);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void info(Object message) {
        invoke(getInfoMethod(), message);
    }

    public static void info(String message, Object... arguments) {
        invoke(getInfo1Method(), message, arguments);
    }

    public static void error(Throwable throwable, String message, Object... arguments) {
        invoke(getErrorMethod(), throwable, message, arguments);
    }

}
